﻿using System;
using System.Windows;

namespace LogoFX.Infra.Interactivity
{
    [Obsolete("Use System.Interactivity.Behavior<T>")]
    public class BehaviorBase<T> where T : BehaviorBase<T>
    {
        private FrameworkElement m_owner;

        protected FrameworkElement Owner
        {
            get { return m_owner; }
        }

        protected virtual void OnDetach()
        {

        }
        protected virtual void OnAttach()
        {

        }

        ///////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets <see cref="InstanceProperty"/> value of a <see cref="DependencyObject"/>.
        /// </summary>
        /// <param name="obj">A dependency object, which contains <c>Instance</c> propery.</param>
        /// <returns><c>Instance</c> property value.</returns>
        public static T GetInstance(DependencyObject obj)
        {
            return (T)obj.GetValue(InstanceProperty);
        }

        /// <summary>
        /// Sets <see cref="InstanceProperty"/> value of a <see cref="DependencyObject"/>.
        /// </summary>
        /// <param name="obj">A dependency object, which contains <c>Instance</c> propery.</param>
        /// <param name="value">New <c>Instance</c> propery value.</param>
        public static void SetInstance(DependencyObject obj, T value)
        {
            obj.SetValue(InstanceProperty, value);
        }

        /// <summary>
        /// Defines the <c>Instance</c> dependency property.
        /// </summary>
        public static readonly DependencyProperty InstanceProperty = DependencyProperty.RegisterAttached(
          "Instance",
          typeof(T),
          typeof(BehaviorBase<T>),
          new PropertyMetadata(null));

        ///////////////////////////////////////////////////////////////////

        protected static T GetOrAttach(FrameworkElement owner)
        {
            T behavior;
            if ((behavior = GetInstance(owner)) == null)
            {
                behavior = Activator.CreateInstance<T>();
                behavior.m_owner = owner;
                SetInstance(owner, behavior);
                behavior.OnAttach();
            }
            return behavior;
        }
        protected static void Detach(FrameworkElement owner)
        {
            T t = GetInstance(owner);
            if (t != null)
                t.Detach();
        }

        protected void Detach()
        {
            OnDetach();
            SetInstance(m_owner, null);
            m_owner = null;
        }

    }
}
